import { useState, useEffect } from 'react';
import { Button, Table, Modal, Switch } from 'antd';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import DialogModalForm, { Item } from './DialogModalForm';
import { getRoles } from '../../../api/role.js'
const { confirm } = Modal;

// let rolesList: Item[] = [
//   {
//     key: 1,
//     name: "超级管理员",
//     roleKey: "SuperAdministrator",
//     description: "超级管理员，拥有至高无上的权限",
//     createUser: "admin",
//     updateUser: "admin",
//     createTime: "2019-05-02",
//     updateTime: "2019-05-02",
//     isEnable: 1,
//     permission: []
//   },
//   {
//     key: 2,
//     name: "管理员",
//     roleKey: "Administrator",
//     description: "管理员，仅次于超级管理员",
//     createUser: "admin",
//     updateUser: "admin",
//     createTime: "2019-05-02",
//     updateTime: "2019-05-02",
//     isEnable: 1,
//     permission: []
//   }
// ]

const Role = () => {

  // const onSelectChange = (selectedRowKeys: any) => {
  //   setSelectedRowKeys(selectedRowKeys)
  // }
  const [state, setstate] = useState<Item | null>();
  const [dialogType, setDialogType] = useState<string>('new');
  const [dialogVisible, setDialogVisible] = useState<boolean>(false);
  const [rolesListData, setRolesListData] = useState<Item[]>([]);

  useEffect(()=> {
    getRoles().then((response: any)=> {

      setRolesListData(response.data)

    })
  }, [])

  const handleDelete = (record: Item) => {
    confirm({
      title: 'Do you want to delete these items?',
      icon: <ExclamationCircleOutlined />,
      content: 'When clicked the OK button, this dialog will be closed after 1 second',
      onOk() {
        return new Promise((resolve, reject) => {
          setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
        }).catch(() => console.log('Oops errors!'));
      },
      onCancel() {},
    });
  }

  const handleEdit = (record: Item) => {
    setstate(record);
    setDialogType('edit')
    setDialogVisible(true)
  }

  const handleAddRole = () => {
    setDialogType('new')
    setDialogVisible(true)
    setstate(null);
  }

  const handleSetDialogVisible = (bool: boolean) => {
    setDialogVisible(bool)
  }

  const onChange = (checked: any, record: Item) => {
    const enable = record.isEnable;
    let text = "是否禁用角色？";
    if (!enable) {
      text = "确认启用该角色？";
    }
    confirm({
      title: text,
      icon: <ExclamationCircleOutlined />,
      onOk() {
        return new Promise((resolve: any, reject: any) => {
          // setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
          // record.isEnable = enable ? 0 : 1; 
          const tempRoleState = [...rolesListData];
          tempRoleState.filter((item: any) => {
            if(item.key === record.key) {
              record.isEnable = enable ? 0 : 1; 
            }
            return item;
          })
          setRolesListData(tempRoleState);
          resolve()
        }).catch(() => console.log('Oops errors!'));
      },
      onCancel() {},
    });
  }

  const columns = [
    {
      title: '角色名',
      dataIndex: 'name'
    },
    {
      title: '角色代码',
      dataIndex: 'roleKey'
    },
    {
      title: '角色描述',
      dataIndex: 'description'
    },
    {
      title: '创建人',
      dataIndex: 'updateUser'
    },
    {
      title: '最近更新时间',
      dataIndex: 'updateTime'
    },
    {
      title: '状态',
      dataIndex: 'isEnable',
      render: (text: any, record: Item) => {
        return (<><Switch checked={text ? true : false} onClick={(checked)=>(onChange(checked, record))} /></>)
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text: any, record: Item) => <><Button type="link" icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>编辑</Button><Button type="link" danger icon={<DeleteOutlined />} size="small" onClick={() => handleDelete(record)}>删除</Button></>
    }
  ]

  return (<>
    <Button type="primary" onClick={handleAddRole} className="mb-20">添加角色</Button>
    <Table columns={columns} dataSource={rolesListData} />
    {
      dialogVisible && <DialogModalForm 
      dialogVisible={dialogVisible}
      handleSetDialogVisible={handleSetDialogVisible}
      dialogType={dialogType}
      record={state} />
    }
  </>)
}

export default Role;
